import { Component, OnInit, Input } from '@angular/core'
import { Widget } from '../../model'
import { JsonApiService } from '../../../../core/api/json-api.service'

declare var echarts: any
let chart = null
let timer = null

@Component({
  selector: 'echarts',
  templateUrl: './echarts.html',
  styleUrls: ['./echarts.css']
})
export class EchartsComponent implements OnInit, Widget {
  @Input() componentData: any

  chartOption = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      top: '40',
      left: '40',
      bottom: '30',
      right: '20'
    },
    xAxis: {
      boundaryGap: false,
      type: 'category',
      axisTick: {
        show: false
      },
      data: (function () {
        let now = new Date()
        const res = []
        let len = 30
        while (len--) {
          res.unshift(now.toLocaleTimeString().replace(/^\D*/, ''))
          now = new Date(now.getTime() - 2000)
        }
        return res
      })()
    },
    yAxis: [
      {
        type: 'value',
        name: '价格',
        splitLine: {
          show: false
        }
      }
    ],
    series: [
      {
        name: '收入',
        type: 'line',
        symbol: 'none',
        lineStyle: {
          width: 1,
          color: '#409EFF'
        },
        areaStyle: {
          opacity: 0.1,
          color: '#79bbff'
        },
        data: (function () {
          const res = []
          let len = 30
          while (len--) {
            res.push(Math.round(Math.random() * 0))
          }
          return res
        })()
      }
    ]
  }
  constructor(private jsonApiService: JsonApiService) {}
  ngOnInit() {}

  ngAfterViewInit() {
    chart = echarts.init(document.getElementById('chart'))
    this.setOptions(this.chartOption)
    this.setData()
    window.addEventListener('resize', this.resizeChart)
  }

  ngOnDestroy() {
    if (!chart) return
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    window.removeEventListener('resize', this.resizeChart)
    chart.dispose()
    chart = null
  }

  resizeChart() {
    chart && chart.resize()
  }

  setOptions(option: any) {
    if (chart) {
      chart.setOption(option)
    }
  }

  setData() {
    timer = setInterval(() => {
      this.chartOption.series[0].data.shift()
      this.chartOption.series[0].data.push(Math.round(Math.random() * 100))

      this.chartOption.xAxis.data.shift()
      this.chartOption.xAxis.data.push(new Date().toLocaleTimeString().replace(/^\D*/, ''))
      this.setOptions(this.chartOption)
    }, 2100)
  }
}
